package cn.pubinfo.util;

import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by zck on 2017/7/10.
 */
@Component
public class FileUtil {
    public String saveMultipartFile(MultipartFile file, String dir){
        if (file != null){
            String pathRoot = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
            if (!file.isEmpty()){
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String contentType = file.getContentType();
                String fileType = contentType.substring(contentType.indexOf("/") + 1);
                String path = "/" + dir + "/" + uuid + "." + fileType;
                try {
                    file.transferTo(new File(pathRoot + path));
                    return path;
                } catch (IOException e) {
//                todo
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public String saveByte(byte[] bytes, String dir, String suffix){
        if (bytes != null){
//            String pathRoot = "C:\\Users\\kuancz\\Desktop\\";
            String pathRoot = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String path = dir + "/" + uuid + "." + suffix;
            File file = new File(pathRoot + path);
            try{
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(bytes);
                fileOutputStream.close();
                return "/" + path;
            } catch (IOException e) {
                // todo
                e.printStackTrace();
            }
        }
        return null;
    }

}
